package com.example.websocket.controller;

import com.example.websocket.model.ChatMessage;
import com.example.websocket.service.MessageService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.handler.annotation.DestinationVariable;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.List;

/**
 * 消息控制器
 */
@RestController
@RequestMapping("/api/messages")
@RequiredArgsConstructor
public class MessageController {

    private final MessageService messageService;

    // 删除单个消息，只能删除自己本地记录的消息
    @DeleteMapping("/{messageId}")
    public ResponseEntity<Void> deleteMessage(@PathVariable String messageId, Principal principal) {
        String currentUserId = principal.getName(); // 假设这里返回的是用户ID
        messageService.deleteMessage(messageId, currentUserId);
        return ResponseEntity.noContent().build();
    }

    // 消息编辑重发
    @PutMapping("/{messageId}")
    public ResponseEntity<Void> editMessage(@PathVariable String messageId, @RequestBody ChatMessage updatedMessage, Principal principal) {
        String currentUserId = principal.getName(); // 假设这里返回的是用户ID
        messageService.editMessage(messageId, updatedMessage, currentUserId);
        return ResponseEntity.noContent().build();
    }

    // 消息撤回，在发出后指定时间内可以撤回，撤回的消息不会出现在双方的聊天记录中
    @DeleteMapping("/{messageId}/revoke")
    public ResponseEntity<Void> revokeMessage(@PathVariable String messageId, Principal principal) {
        String currentUserId = principal.getName(); // 假设这里返回的是用户ID
        messageService.revokeMessage(messageId, currentUserId);
        return ResponseEntity.noContent().build();
    }

    // 获取与指定用户的私聊历史，采用分页查询
    @GetMapping("/private/{targetUserId}")
    public ResponseEntity<List<ChatMessage>> getPrivateChatHistory(@PathVariable String targetUserId, Principal principal) {
        String currentUserId = principal.getName(); // 假设这里返回的是用户ID
        List<ChatMessage> chatHistory = messageService.getPrivateChatHistory(currentUserId, targetUserId);
        return ResponseEntity.ok(chatHistory);
    }

    // 获取指定群聊的历史消息,采用分页查询
    @GetMapping("/group/{groupId}")
    public ResponseEntity<List<ChatMessage>> getGroupChatHistory(@PathVariable String groupId, Principal principal) {
        String currentUserId = principal.getName(); // 验证用户是否属于该群聊
        List<ChatMessage> chatHistory = messageService.getGroupChatHistory(groupId);
        return ResponseEntity.ok(chatHistory);
    }

}